using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.UI.Windowing;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Pickers;
using Windows.Storage;
using WinRT.Interop;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace App4
{
    public class DeviceInfo
    {
        public string DeviceName { get; set; }
        public string IpAddress { get; set; }
    }

    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        private List<DeviceInfo> _devices = new List<DeviceInfo>();
        private List<string> _remoteFiles = new List<string>();
        private string _sharedPath = string.Empty;
        private string _downloadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LanTransfer");
        private UdpClient _udpClient;
        private TcpListener _tcpListener;
        private FileTransferManager _fileTransferManager;
        private const int DiscoveryPort = 8888;
        private const int FileTransferPort = 8889;

        public MainWindow()
        {
            InitializeComponent();
            Initialize();
            LoadSettings();
            
            // 扩展内容到标题栏区域，实现无边框效果
            this.ExtendsContentIntoTitleBar = true;
            
            // 设置自定义标题栏
            this.SetTitleBar(AppTitleBar);
            
            // 设置拖拽区域
            DragArea.PointerPressed += DragArea_PointerPressed;
        }

        // 主题切换事件处理
        private void ThemeRadioButton_Click(object sender, RoutedEventArgs e)
        {
            if (LightThemeRadio.IsChecked == true)
            {
                ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Light;
                SaveSetting("Theme", "Light");
            }
            else if (DarkThemeRadio.IsChecked == true)
            {
                ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Dark;
                SaveSetting("Theme", "Dark");
            }
            else if (SystemThemeRadio.IsChecked == true)
            {
                ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Default;
                SaveSetting("Theme", "System");
            }
        }

        // 模糊效果开关事件处理
        private void BlurToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            if (this.Content is Grid rootGrid)
            {
                if (rootGrid.Background is AcrylicBrush acrylicBrush)
                {
                    // 在WinUI 3中，我们通过调整TintOpacity来控制模糊效果
                    acrylicBrush.TintOpacity = BlurToggleSwitch.IsOn ? 0.8 : 1.0;
                }
            }
            SaveSetting("BlurEnabled", BlurToggleSwitch.IsOn.ToString());
        }

        // GPU加速开关事件处理
        private void GPUToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            // 在WinUI 3中没有直接的GPU加速控制API
            // 这里我们通过调整亚克力材质的属性来模拟GPU加速效果
            if (this.Content is Grid rootGrid)
            {
                if (rootGrid.Background is AcrylicBrush acrylicBrush)
                {
                    if (GPUToggleSwitch.IsOn)
                    {
                        // 启用GPU加速时使用更高质量的设置
                        acrylicBrush.TintLuminosityOpacity = 0.5;
                    }
                    else
                    {
                        // 禁用GPU加速时使用更高效的设置
                        acrylicBrush.TintLuminosityOpacity = 0.8;
                    }
                }
            }
            SaveSetting("GPUEnabled", GPUToggleSwitch.IsOn.ToString());
        }

        /// <summary>
        /// 最小化窗口按钮事件处理
        /// </summary>
        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前窗口的演示器
            if (this.AppWindow?.Presenter is OverlappedPresenter presenter)
            {
                // 最小化窗口
                presenter.Minimize();
            }
        }

        /// <summary>
        /// 关闭窗口按钮事件处理
        /// </summary>
        private void ResetSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 重置主题为跟随系统
            SystemThemeRadio.IsChecked = true;
            ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Default;

            // 重置模糊效果为关闭
            BlurToggleSwitch.IsOn = false;
            if (this.Content is Grid rootGrid && rootGrid.Background is AcrylicBrush acrylicBrush)
            {
                acrylicBrush.TintOpacity = 1.0;

                // 重置GPU加速为开启
                GPUToggleSwitch.IsOn = true;
                acrylicBrush.TintLuminosityOpacity = 0.5;
            }

            // 清除保存的设置
            try
            {
                string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App4Settings");
                string filePath = Path.Combine(settingsPath, "settings.txt");
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"重置设置失败: {ex.Message}");
            }
        }

        private void SaveSetting(string key, string value)
        {
            try
            {
                // 使用本地文件存储代替ApplicationData，以确保单文件模式兼容
                string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App4Settings");
                Directory.CreateDirectory(settingsPath);
                string filePath = Path.Combine(settingsPath, "settings.txt");

                // 读取现有设置
                Dictionary<string, string> settings = new Dictionary<string, string>();
                if (File.Exists(filePath))
                {
                    foreach (string line in File.ReadAllLines(filePath))
                    {
                        string[] parts = line.Split('=', 2);
                        if (parts.Length == 2)
                        {
                            settings[parts[0]] = parts[1];
                        }
                    }
                }

                // 更新设置
                settings[key] = value;

                // 保存设置
                List<string> lines = new List<string>();
                foreach (var pair in settings)
                {
                    lines.Add($"{pair.Key}={pair.Value}");
                }
                File.WriteAllLines(filePath, lines);
            }
            catch (Exception ex)
            {
                // 记录错误但不中断程序
                System.Diagnostics.Debug.WriteLine($"保存设置失败: {ex.Message}");
            }
        }

        private void LoadSettings()
        {
            // 使用本地文件存储加载设置
            string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App4Settings");
            string filePath = Path.Combine(settingsPath, "settings.txt");
            Dictionary<string, string> settings = new Dictionary<string, string>();

            if (File.Exists(filePath))
            {
                try
                {
                    foreach (string line in File.ReadAllLines(filePath))
                    {
                        string[] parts = line.Split('=', 2);
                        if (parts.Length == 2)
                        {
                            settings[parts[0]] = parts[1];
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"加载设置失败: {ex.Message}");
                }
            }

            // 加载主题设置
            if (settings.TryGetValue("Theme", out string theme))
            {
                if (theme == "Light")
                {
                    LightThemeRadio.IsChecked = true;
                    ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Light;
                }
                else if (theme == "Dark")
                {
                    DarkThemeRadio.IsChecked = true;
                    ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Dark;
                }
                else
                {
                    SystemThemeRadio.IsChecked = true;
                    ((FrameworkElement)this.Content).RequestedTheme = ElementTheme.Default;
                }
            }

            // 加载模糊效果设置
            if (settings.TryGetValue("BlurEnabled", out string blurValue))
            {
                if (bool.TryParse(blurValue, out bool blurEnabled))
                {
                    BlurToggleSwitch.IsOn = blurEnabled;
                    if (this.Content is Grid rootGrid && rootGrid.Background is AcrylicBrush acrylicBrush)
                    {
                        acrylicBrush.TintOpacity = blurEnabled ? 0.8 : 1.0;
                    }
                }
            }

            // 加载GPU加速设置
            if (settings.TryGetValue("GPUEnabled", out string gpuValue))
            {
                if (bool.TryParse(gpuValue, out bool gpuEnabled))
                {
                    GPUToggleSwitch.IsOn = gpuEnabled;
                    if (this.Content is Grid rootGrid && rootGrid.Background is AcrylicBrush acrylicBrush)
                    {
                        acrylicBrush.TintLuminosityOpacity = gpuEnabled ? 0.5 : 0.8;
                    }
                }
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 最大化/还原窗口按钮事件处理
        /// </summary>
        private void MaximizeButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前窗口的演示器
            if (this.AppWindow?.Presenter is OverlappedPresenter presenter)
            {
                // 检查当前窗口状态并执行相应操作
                if (presenter.State == OverlappedPresenterState.Maximized)
                {
                    // 还原窗口
                    presenter.Restore();
                    MaximizeButton.Content = "🗖";
                    ToolTipService.SetToolTip(MaximizeButton, "最大化");
                }
                else
                {
                    // 最大化窗口
                    presenter.Maximize();
                    MaximizeButton.Content = "🗗";
                    ToolTipService.SetToolTip(MaximizeButton, "还原");
                }
            }
        }

        private void DragArea_PointerPressed(object sender, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            // 拖拽功能将通过设置标题栏自动处理
        }

        private void Initialize()
        {
            // 设置默认下载路径
            if (!Directory.Exists(_downloadPath))
            {
                Directory.CreateDirectory(_downloadPath);
            }
            DownloadPathText.Text = _downloadPath;

            // 添加窗口关闭事件处理
            this.Closed += MainWindow_Closed;

            // 初始化文件传输管理器
            _fileTransferManager = new FileTransferManager();

            // 初始化UDP客户端用于设备发现
            _udpClient = new UdpClient(DiscoveryPort);
            _udpClient.EnableBroadcast = true;
            Task.Run(() => ListenForDiscoveryMessages());

            // 初始化TCP监听器用于文件传输
            _tcpListener = new TcpListener(IPAddress.Any, FileTransferPort);
            _tcpListener.Start();
            Task.Run(() => AcceptFileTransferConnections());

            // 自动发现设备
            DiscoverDevices();

            // 添加设备选择事件
            DevicesListView.SelectionChanged += DevicesListView_SelectionChanged;
        }

        private async void DevicesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DevicesListView.SelectedItem is DeviceInfo selectedDevice)
            {
                // 获取远程设备的文件列表
                _remoteFiles = await GetRemoteFileList(selectedDevice.IpAddress);

                // 更新UI显示文件列表
                this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                {
                    RemoteFilesListView.ItemsSource = null;
                    RemoteFilesListView.ItemsSource = _remoteFiles;
                    DownloadButton.IsEnabled = _remoteFiles.Count > 0;
                });
            }
        }

        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            if (DevicesListView.SelectedItem is DeviceInfo selectedDevice && RemoteFilesListView.SelectedItem is string selectedFile)
            {
                var downloadButton = sender as Button;
                downloadButton.IsEnabled = false;
                
                DownloadProgressBar2.Visibility = Visibility.Visible;
                DownloadStatusText.Text = "正在准备下载...";

                try
                {
                    int threadCount = (int)ThreadCountSlider.Value;
                    
                    await FileTransferManager.DownloadFileWithThreads(selectedDevice.IpAddress, selectedFile, _downloadPath, threadCount,
                        new Progress<FileTransferManager.DownloadProgress>(progress =>
                        {
                            this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                            {
                                DownloadProgressBar2.Value = progress.Percentage;
                                DownloadProgressText.Text = $"{progress.BytesTransferred / 1024 / 1024:F1} MB / {progress.TotalBytes / 1024 / 1024:F1} MB ({progress.Percentage}%)";
                                DownloadSpeedText.Text = $"{progress.Speed / 1024:F0} KB/s";
                                DownloadTimeText.Text = progress.EstimatedTimeRemaining;
                            });
                        }));

                    this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                    {
                        DownloadStatusText.Text = "下载完成 ✓";
                        ShowTeachingTip("下载完成", $"文件已保存到: {_downloadPath}", InfoBarSeverity.Success);
                    });
                    
                    // 3秒后隐藏进度条
                    await Task.Delay(3000);
                    DownloadProgressBar2.Visibility = Visibility.Collapsed;
                }
                catch (Exception ex)
                {
                    this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                    {
                        DownloadStatusText.Text = "下载失败";
                        ShowTeachingTip("下载失败", ex.Message, InfoBarSeverity.Error);
                    });
                }
                finally
                {
                    this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                    {
                        DownloadProgressBar.Visibility = Visibility.Collapsed;
                        downloadButton.IsEnabled = true;
                    });
                }
            }
            else
            {
                ShowTeachingTip("未选择文件", "请先选择要下载的文件", InfoBarSeverity.Warning);
            }
        }

        // 窗口关闭事件处理方法
        private void MainWindow_Closed(object sender, WindowEventArgs args)
        {
            // 释放资源
            _udpClient?.Close();
            _tcpListener?.Stop();
        }

        private async Task<List<string>> GetRemoteFileList(string ipAddress)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    await client.ConnectAsync(ipAddress, FileTransferPort);

                    using (var stream = client.GetStream())
                    {
                        // 发送获取文件列表请求
                        byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes("GET_FILE_LIST");
                        byte[] lengthBytes = BitConverter.GetBytes(requestBytes.Length);
                        await stream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
                        await stream.WriteAsync(requestBytes, 0, requestBytes.Length);

                        // 接收文件列表
                        byte[] listLengthBytes = new byte[4];
                        await stream.ReadAsync(listLengthBytes, 0, listLengthBytes.Length);
                        int listLength = BitConverter.ToInt32(listLengthBytes, 0);

                        byte[] listBytes = new byte[listLength];
                        await stream.ReadAsync(listBytes, 0, listBytes.Length);
                        string fileListString = System.Text.Encoding.UTF8.GetString(listBytes);

                        return fileListString.Split('|').ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取文件列表时出错: {ex.Message}");
                return new List<string>();
            }
        }

        private async void AcceptFileTransferConnections()
        {
            try
            {
                while (true)
                {
                    TcpClient client = await _tcpListener.AcceptTcpClientAsync();
                    Task.Run(() => HandleFileTransferClient(client));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"接受文件传输连接时出错: {ex.Message}");
            }
        }

        private async void HandleFileTransferClient(TcpClient client)
        {
            try
            {
                using (client)
                using (var stream = client.GetStream())
                {
                    // 读取请求长度
                    byte[] lengthBytes = new byte[4];
                    await stream.ReadAsync(lengthBytes, 0, lengthBytes.Length);
                    int requestLength = BitConverter.ToInt32(lengthBytes, 0);

                    // 读取请求内容
                    byte[] requestBytes = new byte[requestLength];
                    await stream.ReadAsync(requestBytes, 0, requestBytes.Length);
                    string request = System.Text.Encoding.UTF8.GetString(requestBytes);

                    if (request == "GET_FILE_LIST")
                    {
                        // 发送文件列表
                        await SendFileList(stream);
                    }
                    else if (File.Exists(request) || Directory.Exists(request))
                    {
                        // 发送文件
                        await SendFile(stream, request);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理文件传输客户端时出错: {ex.Message}");
            }
        }

        private async Task SendFileList(NetworkStream stream)
        {
            List<string> fileList = new List<string>();

            if (!string.IsNullOrEmpty(_sharedPath))
            {
                if (Directory.Exists(_sharedPath))
                {
                    // 如果是文件夹，添加文件夹中的所有文件
                    string[] files = Directory.GetFiles(_sharedPath, "*.*", SearchOption.AllDirectories);
                    fileList.AddRange(files);
                }
                else if (File.Exists(_sharedPath))
                {
                    // 如果是单个文件，添加该文件
                    fileList.Add(_sharedPath);
                }
            }

            // 将文件列表转换为字符串
            string fileListString = string.Join("|", fileList);
            byte[] listBytes = System.Text.Encoding.UTF8.GetBytes(fileListString);
            byte[] lengthBytes = BitConverter.GetBytes(listBytes.Length);

            // 发送文件列表
            await stream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
            await stream.WriteAsync(listBytes, 0, listBytes.Length);
        }

        private async Task SendFile(NetworkStream stream, string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("文件不存在", filePath);
            }

            // 获取文件信息
            FileInfo fileInfo = new FileInfo(filePath);
            long fileSize = fileInfo.Length;
            string fileName = fileInfo.Name;

            // 发送文件信息
            byte[] fileInfoBytes = new byte[16];
            BitConverter.GetBytes(fileSize).CopyTo(fileInfoBytes, 0);
            BitConverter.GetBytes(fileName.Length).CopyTo(fileInfoBytes, 8);
            await stream.WriteAsync(fileInfoBytes, 0, fileInfoBytes.Length);

            // 发送文件名
            byte[] fileNameBytes = System.Text.Encoding.UTF8.GetBytes(fileName);
            await stream.WriteAsync(fileNameBytes, 0, fileNameBytes.Length);

            // 等待客户端请求块信息
            byte[] chunkInfo = new byte[16];
            await stream.ReadAsync(chunkInfo, 0, chunkInfo.Length);
            long startPosition = BitConverter.ToInt64(chunkInfo, 0);
            long endPosition = BitConverter.ToInt64(chunkInfo, 8);

            // 发送文件块
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                fileStream.Position = startPosition;
                byte[] buffer = new byte[8192];
                long bytesRemaining = endPosition - startPosition + 1;

                while (bytesRemaining > 0)
                {
                    int bytesToRead = (int)Math.Min(buffer.Length, bytesRemaining);
                    int bytesRead = await fileStream.ReadAsync(buffer, 0, bytesToRead);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    await stream.WriteAsync(buffer, 0, bytesRead);
                    bytesRemaining -= bytesRead;
                }
            }
        }



        private void ShowTeachingTip(string title, string message, InfoBarSeverity severity)
        {
            // 创建现代的通知提示
            var infoBar = new InfoBar
            {
                Title = title,
                Message = message,
                Severity = severity,
                IsOpen = true,
                IsClosable = true,
                Margin = new Thickness(0, 0, 0, 12)
            };

            // 添加到当前页面的根网格
            if (Content is Grid rootGrid)
            {
                // 将InfoBar添加到最顶层
                Grid.SetRow(infoBar, 0);
                Grid.SetRowSpan(infoBar, 2);
                rootGrid.Children.Add(infoBar);
                
                // 5秒后自动关闭
                DispatcherQueue.TryEnqueue(async () =>
                {
                    await Task.Delay(5000);
                    if (rootGrid.Children.Contains(infoBar))
                    {
                        rootGrid.Children.Remove(infoBar);
                    }
                });
            }
        }

        private void DiscoverDevicesButton_Click(object sender, RoutedEventArgs e)
        {
            DiscoverDevices();
        }

        private void DiscoverDevices()
        {
            _devices.Clear();
            DevicesListView.ItemsSource = null;
            DevicesListView.ItemsSource = _devices;

            // 发送广播消息
            byte[] data = System.Text.Encoding.UTF8.GetBytes("DISCOVER");
            _udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, DiscoveryPort));

            // 添加本地设备（用于测试）
            AddDevice(Environment.MachineName, GetLocalIPAddress());
        }

        private async void ListenForDiscoveryMessages()
        {
            try
            {
                while (true)
                {
                    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = _udpClient.Receive(ref remoteEP);
                    string message = System.Text.Encoding.UTF8.GetString(data);

                    if (message.StartsWith("DISCOVER"))
                    {
                        // 响应发现请求
                        byte[] responseData = System.Text.Encoding.UTF8.GetBytes($"RESPONSE:{Environment.MachineName}");
                        _udpClient.Send(responseData, responseData.Length, remoteEP);
                    }
                    else if (message.StartsWith("RESPONSE:"))
                    {
                        string deviceName = message.Substring(9);
                        string ipAddress = remoteEP.Address.ToString();

                        // 确保在UI线程上更新
                        this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
                        {
                            AddDevice(deviceName, ipAddress);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
            }
        }

        private void AddDevice(string deviceName, string ipAddress)
        {
            // 检查设备是否已存在
            if (!_devices.Any(d => d.IpAddress == ipAddress))
            {
                _devices.Add(new DeviceInfo { DeviceName = deviceName, IpAddress = ipAddress });
                DevicesListView.ItemsSource = null;
                DevicesListView.ItemsSource = _devices;
            }
        }

        private string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return "127.0.0.1";
        }

        private async void SelectShareButton_Click(object sender, RoutedEventArgs e)
        {
            if (ShareFolderRadio.IsChecked == true)
            {
                var folderPicker = new FolderPicker();
                folderPicker.FileTypeFilter.Add("*");

                // 获取窗口句柄
                var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
                WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hWnd);

                var folder = await folderPicker.PickSingleFolderAsync();
                if (folder != null)
                {
                    _sharedPath = folder.Path;
                    SharedPathText.Text = _sharedPath;
                }
            }
            else
            {
                var filePicker = new FileOpenPicker();
                filePicker.FileTypeFilter.Add("*");

                // 获取窗口句柄
                var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
                WinRT.Interop.InitializeWithWindow.Initialize(filePicker, hWnd);

                var file = await filePicker.PickSingleFileAsync();
                if (file != null)
                {
                    _sharedPath = file.Path;
                    SharedPathText.Text = _sharedPath;
                }
            }
        }

        private async void SelectDownloadPathButton_Click(object sender, RoutedEventArgs e)
        {
            var folderPicker = new FolderPicker();
            folderPicker.FileTypeFilter.Add("*");

            // 获取窗口句柄
            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
            WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hWnd);

            var folder = await folderPicker.PickSingleFolderAsync();
            if (folder != null)
            {
                _downloadPath = folder.Path;
                DownloadPathText.Text = _downloadPath;
            }
        }
    }
}
